package com.xg.java.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xg.java.entity.NetworkPan;
import com.xg.java.service.NetworkPanService;
import com.xg.java.util.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import static com.xg.java.util.FileUploadUtil.uploadFileByPath;

/**
 * @description network_pan控制器
 * @author wang
 * @date 2021-12-17
 */
@Slf4j
@RestController
@Api(tags = "网盘功能")
@RequestMapping("/networkPan")
public class NetworkPanController {

    @Autowired
    private NetworkPanService networkPanService;

    @PostMapping("/saveFile")
    @ApiOperation("保存文件或文件夹")
    public Object saveFile(NetworkPan pan, MultipartFile file) throws IOException {
        if (pan.getId()==null) {
            pan.setCreateTime(new Date());
        }
        if (pan.getType()==1&&pan.getPid()!=0)return new CommonResult().validateFailed("不能嵌套多层文件夹");
        if (pan.getType()==0) {
            pan.setFileSize(file.getSize());
            pan.setName(file.getOriginalFilename());
            pan.setPath(uploadFileByPath(file, pan.getUserId()).replaceAll("\\\\","/"));
        }else if (pan.getType()==1&&networkPanService.getOne(Wrappers.lambdaQuery(new NetworkPan()).eq(NetworkPan::getUserId, pan.getUserId()).eq(NetworkPan::getPid,pan.getPid()).eq(NetworkPan::getName,pan.getName()))!=null)
            return new CommonResult().validateFailed("不能存在同名文件夹");
        if (networkPanService.saveOrUpdate(pan)) {
            return new CommonResult().success(pan.getId());
        }
        return new CommonResult().failed();
    }

    @ApiOperation("获取所有网盘文件")
    @GetMapping("/getAllFile")
    public Object getAllFile(Long userId){
        System.out.println("当前会话是否登录：" + StpUtil.isLogin());
        if (userId==null)return new CommonResult().validateFailed("参数异常");
        List<NetworkPan> list = networkPanService.list(Wrappers.lambdaQuery(new NetworkPan())
                .eq(NetworkPan::getUserId, userId)
                .eq(NetworkPan::getPid,0)
                .orderByDesc(NetworkPan::getType)
                .orderByDesc(NetworkPan::getCreateTime)
        );
        list.forEach(a->{
            if (a.getType()==1)a.setChilds(networkPanService.list(Wrappers.lambdaQuery(new NetworkPan()).eq(NetworkPan::getUserId, userId).eq(NetworkPan::getPid,a.getId())));
        });
        return new CommonResult().success(list);
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/deleteFile/{id}")
    public Object deleteFileById(@PathVariable Long id){
        NetworkPan byId = networkPanService.getById(id);
        if (networkPanService.removeById(id)) {
            if (byId.getType()==0){
                File file = new File(byId.getPath());
                if (file.isFile()) {
                    file.delete();
                }
            }
            return new CommonResult().success();
        }
        return new CommonResult().failed();
    }

    @ApiOperation("下载文件")
    @GetMapping("/download")
    public Object downloadFile(String filePath, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {

        String FullPath =filePath;//将文件的统一储存路径和文件名拼接得到文件全路径
        File packetFile = new File(FullPath);
        String fileName = packetFile.getName(); //下载的文件名
        File file = new File(FullPath);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            try {
                //设置响应的数据类型是html文本，并且告知浏览器，使用UTF-8 来编码。
                response.setContentType("text/html;charset=UTF-8");

                //String这个类里面， getBytes()方法使用的码表，是UTF-8，  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                String csn = Charset.defaultCharset().name();

                System.out.println("默认的String里面的getBytes方法使用的码表是： " + csn);

                //1. 指定浏览器看这份数据使用的码表
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                OutputStream os = response.getOutputStream();

                os.write("对应文件不存在".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
//                return R.error("-1","对应文件不存在");
        }
        return null;
    }


}